package il.adscan.scan.impl;

import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTableRow;
import il.adscan.domain.Advertisement;
import il.adscan.domain.AdvertisementFilter;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

public class WinWinScanner extends BaseScanner {

    @Override
    protected List<Advertisement> scrapPageData(HtmlPage htmlPage) throws IOException {
        Document doc = Jsoup.parse(htmlPage.asXml());
        Elements elements = doc.select("#gridWrapper1 [onclick*=openGridTr]");
        List<Advertisement> advertisementList = new ArrayList<>();
        int i = 0;
        for (Element element : elements) {
            if (advertisementList.size() >= numberOfItemsToScan && numberOfItemsToScan != -1) {
                break;
            }
            String linkAttr = element.attr("onclick");
            String link = linkAttr.substring(linkAttr.indexOf("http"), linkAttr.indexOf("rnd") + 7);
            System.out.println(i + link);
            Advertisement advertisement = getAdvertisementFromLink(link);
            advertisement.setTimeAdded(element.select(".reddate").html());
            advertisementList.add(advertisement);
            i++;
        }
        return advertisementList;
    }

    protected Elements getElements(Document doc) {
        return doc.select("#gridWrapper1 [onclick*=openGridTr]");
    }

    public Advertisement getAdvertisementFromLink(String link) throws IOException {
//        HtmlPage htmlPage = getHTMLPage(link);
        //Click show cell number and name anchor
        String originalAdvertisementId = getOriginalIdFromLink(link);
//        DomElement elementById = htmlPage.getElementById("ancPhoneNumber_" + originalAdvertisementId);
//        HtmlAnchor showCellNumberAnchor = (HtmlAnchor) elementById;
//        htmlPage = showCellNumberAnchor.click();
//        waitForScript(200);

        Document doc = connect(link);
        //.FRight:not([id])
        Elements textElements = doc.select(".Data");
        Elements imgElements = doc.select(".FLeft");
        Elements priceElements = doc.select(".PriceData");
        Elements extraInfoElements = doc.select(".ExNoteInfo");
        Element contactNameElement = doc.getElementById("ctl00_PageContentPlaceHolder_innerAdContent_innerAdContact_lblContactName");

        String html = doc.toString();
        int beginIndex = html.indexOf("var sPhone = '") + 14;
        String phoneNumber1 = html.substring(beginIndex, html.indexOf("'", beginIndex));
        beginIndex = html.indexOf("var sPhone2 = '") + 15;
        String phoneNumber2 = html.substring(beginIndex, html.indexOf("'", beginIndex));
        beginIndex = html.indexOf("var sExPhone2 = '") + 17;
        String exPhoneNumber2 = html.substring(beginIndex, html.indexOf("'", beginIndex));
        if (StringUtils.isEmpty(exPhoneNumber2)) {
            phoneNumber2 = "";
        }

//        Element phoneNumberElement = doc.getElementById("spnPhoneNumber_" + originalAdvertisementId);
//        Element phoneNumber2Element = doc.getElementById("spnPhone2_" + originalAdvertisementId);

        Advertisement advertisement = new Advertisement();
        advertisement.setSite(getSiteURL());
        advertisement.setOriginalId(originalAdvertisementId);
        advertisement.setPropertyType(getElementValue(textElements.get(0)));
        advertisement.setSubarea(getElementValue(textElements.get(1)));
        advertisement.setCity(getElementValue(textElements.get(2)));
        advertisement.setNeighborhood(getElementValue(textElements.get(3)));
        advertisement.setAddress(getElementValue(textElements.get(4)));
        advertisement.setRoom(getElementValue(textElements.get(5)));
        advertisement.setFloor(getElementValue(textElements.get(6)));//Need to roll out child nodes and concatenate Element html
        advertisement.setStatus(getElementValue(textElements.get(7)));
        advertisement.setAvailableDate(getElementValue(textElements.get(8)));//"Login" field
        advertisement.setSquareMetersSize(getElementValue(textElements.get(9)));//Maybe! Need to roll out child nodes and concatenate Element html

        advertisement.setPrice(StringUtils.trim(priceElements.get(0).childNodes().get(2).toString()));

        advertisement.setParking(isAvailable(imgElements.get(0)));
        advertisement.setAir(isAvailable(imgElements.get(1)));
        advertisement.setSecurityRoom(isAvailable(imgElements.get(2)));
        advertisement.setElevator(isAvailable(imgElements.get(3)));
        advertisement.setHasBalcony(isAvailable(imgElements.get(4)));
        advertisement.setAccessForDisabled(isAvailable(imgElements.get(5)));
        //advertisement.setAccessForDisabled(isAvailable(imgElements.get(6)));// What is דלתות פנדור?
        advertisement.setExtras(getElementValue(extraInfoElements.get(0)));
        advertisement.setUserName(contactNameElement.html());
        advertisement.setUserPhone(phoneNumber1);
        advertisement.setUserPhone2(phoneNumber2);

        return advertisement;
    }

    public boolean isAvailable(Element element) {
        return !element.select(".VImage").isEmpty();
    }

    public String getElementValue(Element element) {
        return element.child(0).html();
    }

    @Override
    protected HtmlPage getPage(int pageNumber, String baseURI) throws IOException {
        String delimiter = getParametersDelimiter(baseURI);
        return getHTMLPage(String.format("%s%sPageNumberBottom=%s&PageNumberTop=%s", baseURI, delimiter, pageNumber, pageNumber));
    }

    @Override
    protected boolean hasNextPage(HtmlPage htmlPage) {
        Document doc = Jsoup.parse(htmlPage.asXml());
        return !doc.select(".pagingArrowRight").isEmpty() && doc.select(".NoResults").isEmpty();
    }

    @Override
    protected boolean isProcessCurrentPage(HtmlPage htmlPage) {
        return Jsoup.parse(htmlPage.asXml()).select(".NoResults").isEmpty();
    }

    @Override
    protected HtmlPage applyFilters(HtmlPage htmlPage, AdvertisementFilter filter) {
        return htmlPage;
    }

    @Override
    public String getSiteURL() {
        return "http://www.winwin.co.il/RealEstate/ForSale/RealEstatePage.aspx";
    }

    public String getOriginalIdFromLink(String link) {
        int beginIndex = link.indexOf("ObjId=") + 6;
        return link.substring(beginIndex, link.indexOf("&", beginIndex));
    }

    @Override
    protected AdScraper getAdScraper(Element element) {
        return new AdScraperWinWin(element, null);
    }

    public int getLastPageNumber() throws IOException {
        HtmlPage htmlPage = getHtmlPageWithAppliedFilters(filter);
        Document doc = Jsoup.parse(htmlPage.asXml());
        return Integer.valueOf(doc.select(".lastPage").html());
    }
}